import userDao from "../Dao/user.js";
import sequelize from "../models/init.js";
import {httpResult} from "../utils/utils.js";

// 同步注册信息
export const syncRegister = async (req, res) => {
  let {id, email, invitation_code, inviter_id, user_name} = req.body;
  console.log(id, email, invitation_code, inviter_id, user_name);
  if (!id || !email || !invitation_code || Number(inviter_id) < 0 || !user_name) {
    throw new Error('注册数据不正确');
  }
  await syncUserInfo(id, email, invitation_code, inviter_id, user_name);
  res.json(httpResult.success({result: true}));
}

// 检查注册信息
export const checkRegister = async (req, res) => {
  let {id} = req.body;
  if (!id) {
    throw new Error('用户id错误');
  }
  let result = await userDao.getUserLock(id);
  if (result) {
    res.json(httpResult.success({result: true}));
    return;
  }
  res.json(httpResult.success({result: false}));
}

async function syncUserInfo(id, email, invitation_code, inviter_id, user_name) {
  const t = await sequelize.transaction();
  try {
    // 添加用户信息
    await userDao.addUser(id, email, invitation_code, inviter_id, user_name, t);
    await t.commit();
  } catch (e) {
    await t.rollback();
    throw new Error('注册失败');
  }
}
